﻿using Microsoft.AspNetCore.Mvc;
using StudentManagement.Models;
using StudentManagement.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace StudentManagement.Controllers
{
    public class HomeController : Controller
    {
        private readonly IStudentRepository _studentRepository;

        // 使用构造函数注入方式，注入IStudentRepository
        public HomeController(IStudentRepository studentRepository)
        {
            _studentRepository = studentRepository;
        }

        public IActionResult Index()
        {
            IEnumerable<Student> students = _studentRepository.GetAllStudents();
            return View(students);
        }

        public IActionResult Details(int? id)
        {
            Student student = _studentRepository.GetStudent(id ?? 1);
            // 使用视图模型ViewModel将数据传递到视图
            HomeDetailsViewModel vm = new()
            {
                Student = student,
                PageTitle = "学生详情"
            };
            return View("Details", vm);// 使用强类型将vm视图模型传递给Test视图进行显示
        }

        [HttpGet]
        public IActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Create(Student student)
        {
            if (ModelState.IsValid)
            {
                Student newStudent = _studentRepository.Add(student);
                return RedirectToAction("details", new { id = newStudent.Id });
            }
            return View();
        }

    }
}
